package com.ruoyi.web.controller.iot;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.iot.domain.mqtt.DeviceStatusInfo;
import com.ruoyi.iot.domain.mqtt.DeviceStatusRequest;
import com.ruoyi.iot.domain.mqtt.config.MqttApiConfig;
import com.ruoyi.iot.domain.mqtt.constants.MqttApiConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

/**
 * mqtt 控制器
 *
 * @Author: 陈江灿
 * @CreateTime: 2025-02-09
 */
@RestController
@RequestMapping("/iot/mqtt")
@Slf4j
public class IotMqttController extends BaseController {

    @Resource
    private MqttApiConfig mqttConfig;

    /**
     * 获取客户端列表
     * @param request
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:mqtt:list')")
    @GetMapping("/list")
    public TableDataInfo getClients(DeviceStatusRequest request) {
        String deviceId = request.getDeviceId();
        String url = String.format(MqttApiConstants.GET_ALL_MQTT_CLIENTS_URL, mqttConfig.getHost(), request.getPageNum(), request.getPageSize());
        if (StringUtils.isNotBlank(deviceId)) {
            url = String.format(MqttApiConstants.GET_MQTT_CLIENT_STATUS_URL, mqttConfig.getHost(), deviceId);
        }
        Object result = exchange(url);
        if (result != null) {
            startPage();
            if (result instanceof JSONObject) {
                JSONObject object = (JSONObject) result;
                List<DeviceStatusInfo> list = JSONArray.parseArray(object.getString("data"), DeviceStatusInfo.class);
                return getDataTable(list);
            } else if (result instanceof JSONArray) {
                JSONArray array = (JSONArray) result;
                List<DeviceStatusInfo> list = array.toJavaList(DeviceStatusInfo.class);
                return getDataTable(list);
            }
        }
        return null;
    }

    /**
     * 获取所有节点
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:mqtt:node')")
    @GetMapping("/node")
    public AjaxResult getNode() {
        String url = String.format(MqttApiConstants.GET_ALL_MQTT_NODE_INFO_URL, mqttConfig.getHost());
        Object result = exchange(url);
        if (result != null) {
            return success(result);
        }
        return error("获取失败");
    }

    /**
     * 获取节点其他信息
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:mqtt:node')")
    @GetMapping("/monitorCurrent")
    public AjaxResult getMonitorCurrent() {
        String url = String.format(MqttApiConstants.GET_MONITOR_CURRENT_URL, mqttConfig.getHost());
        Object result = exchange(url);
        if (result != null) {
            return success(result);
        }
        return error("获取失败");
    }

    /**
     * 踢除某个客户端下线
     * @return
     */
    @PreAuthorize("@ss.hasPermi('iot:mqtt:clients')")
    @GetMapping("/clients/{clientId}")
    public AjaxResult clients(@PathVariable String clientId) {
        String url = mqttConfig.getHost() + MqttApiConstants.GET_CLIENTS_URL + clientId;
        Object result = exchange(url);
        if (result != null) {
            return success(result);
        }
        return error("获取失败");
    }

    /**
     * 交换数据
     *
     * @param url
     * @return
     */
    private Object exchange(String url) {
        HttpResponse response = HttpRequest.get(url)
                .basicAuth(mqttConfig.getApiKey(), mqttConfig.getSecretKey())
                .header("Accept", "application/json")
                .timeout(10000)
                .execute();
        log.info("response=>{}", response.body());
        if (response.getStatus() == 200 && response.body() != null) {
            String body = response.body();
            if (body.startsWith("{")) { // JSON 对象
                return JSONObject.parseObject(body);
            } else if (body.startsWith("[")) { // JSON 数组
                return JSONArray.parseArray(body);
            }
        }
        return null;
    }

}
